package com.cryptape.cita_wallet.activity;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.MapUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.cryptape.cita_wallet.CytonApplication;
import com.cryptape.cita_wallet.adapter.MinerIncomeAdapter;
import com.cryptape.cita_wallet.bean.HttpResponse;
import com.cryptape.cita_wallet.bean.LightNodeBean;
import com.cryptape.cita_wallet.bean.MiningOrderIncomeItem;
import com.cryptape.cita_wallet.bean.MiningWithdrawDetailBean;
import com.cryptape.cita_wallet.bean.MyOrderWallet;
import com.cryptape.cita_wallet.bean.MyOrderWalletBean;
import com.cryptape.cita_wallet.net.callback.CommonCallback;
import com.cryptape.cita_wallet.net.request.HttpRequestMode;
import com.cryptape.cita_wallet.service.http.TokenService;
import com.cryptape.cita_wallet.service.http.WalletService;
import com.cryptape.cita_wallet.util.RSAUtils;
import com.cryptape.cita_wallet.util.db.DBWalletUtil;
import com.cryptape.cita_wallet.util.db.SharePrefUtil;
import com.cryptape.cita_wallet.view.TitleBar;
import com.cryptape.cita_wallet.view.button.CommonButton;
import com.cryptape.cita_wallet.view.dialog.ExtractDialog;
import com.cryptape.cita_wallet.view.dialog.SimpleSelectDialog;
import com.mangoworld.android.R;

import org.web3j.protocol.core.methods.response.EthSendTransaction;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import rx.Subscriber;

/**
 * Created by dengming on 9/3/20.
 */

public class MyIncomeActivity extends NBaseActivity {
    private RecyclerView recyclerView;
    private MinerIncomeAdapter minerAdapter;
    private TitleBar mTitle;
    private TextView tv_balance_mgp;
    private TextView tv_balance_usd;
    private CommonButton btn_extract;
    private TextView tv_income_select_type;
    private TextView tv_balance;
    private TextView tv_income;

    private static final String moneyType = "2";

    @Override
    protected int getContentLayout() {
        return R.layout.activity_miner_income;
    }

    @Override
    protected void initView() {
        recyclerView = findViewById(R.id.miner_income_recycler);
        mTitle = findViewById(R.id.title_bar);
        btn_extract = findViewById(R.id.btn_extract);
        tv_income_select_type = findViewById(R.id.tv_income_select_type);
        tv_income = findViewById(R.id.tv_income);
        mTitle.setOnRightClickListener(new TitleBar.OnRightClickListener() {
            @Override
            public void onRightClick() {
                startActivity(new Intent(MyIncomeActivity.this, MiningIndexActivity.class));
            }
        });
    }

    @Override
    protected void initData() {
        initMinerData();
    }

    private int selectTypeIndex = 0;

    @Override
    protected void initAction() {
//        tv_balance.setText(getString(R.string.));
        btn_extract.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                getConfirmLockView();
                getConfirmTransferView();
            }
        });
        String[] types = new String[]{getString(R.string.profile_hint_item11), getString(R.string.alphago_hint_earnings), getString(R.string.currency_hint_extract), getString(R.string.log_hint_procedurefee)};
        tv_income_select_type.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SimpleSelectDialog dialog = new SimpleSelectDialog(MyIncomeActivity.this, Arrays.asList(types), -1);
                dialog.setMSelected(selectTypeIndex);
                dialog.setOnOkListener((view -> {
                    selectTypeIndex = dialog.getMSelected();
                    tv_income_select_type.setText(types[selectTypeIndex]);
                    dialog.dismiss();

                    List<MiningOrderIncomeItem> newDatas = new ArrayList<>();
                    if (selectTypeIndex == 0) {
//                        newDatas.addAll(datas);
                        minerAdapter.setDatas(datas);
                        minerAdapter.notifyDataSetChanged();
                    } else {
                        for (MiningOrderIncomeItem item : datas) {
                            if (item.getChannelType() == selectTypeIndex) {
                                newDatas.add(item);
                            }
                        }
                        minerAdapter.setDatas(newDatas);
                        minerAdapter.notifyDataSetChanged();
                    }
                }));
            }
        });
    }

    private List<MiningOrderIncomeItem> datas = new ArrayList<>();
    private MyOrderWalletBean mData;
    private MiningWithdrawDetailBean detailBean;

    private void initMinerData() {
        initAdapter();

        String address = DBWalletUtil.getCurrentWallet(CytonApplication.getInstance()).address;
        try {
            Map params = MapUtils.newHashMap();
            params.put("address", address);
            params.put("limit", "100");
            params.put("page", "1");
            String jsonData = GsonUtils.toJson(params);
            String content = RSAUtils.encrypt(jsonData);
            HttpRequestMode.getMyOrderWallet(MyIncomeActivity.this, content, true, new CommonCallback() {
                @Override
                public void onSuccess(Object data, String successMsg, int responseSuccessCode) {
                    if (data == null) {
                        btn_extract.button.setEnabled(false);
                        btn_extract.button.setBackgroundResource(R.drawable.button_corner_gray_shape);
                        return;
                    }
                    mData = (MyOrderWalletBean) data;
                    tv_income.setText(mData.getMoney());
                    List<MiningOrderIncomeItem> incomeItems = mData.getList();
                    if (incomeItems != null) {
                        datas.clear();
                        datas.addAll(incomeItems);
                        minerAdapter.notifyDataSetChanged();
                    }
                    getWithdrawDetail();
                }

                @Override
                public void onFailure(String msg, int responseFailCode) {
                    btn_extract.button.setEnabled(false);
                    btn_extract.button.setBackgroundResource(R.drawable.button_corner_gray_shape);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getWithdrawDetail() {
        try {
            String address = DBWalletUtil.getCurrentWallet(CytonApplication.getInstance()).address;
            Map params = MapUtils.newHashMap();
            params.put("address", address);
            params.put("moneyType", moneyType);
            String jsonData = GsonUtils.toJson(params);
            String content = RSAUtils.encrypt(jsonData);
            HttpRequestMode.getWithdrawIndex(MyIncomeActivity.this, content, true, new CommonCallback() {
                @Override
                public void onSuccess(Object data, String successMsg, int responseSuccessCode) {
                    detailBean = (MiningWithdrawDetailBean) data;
                }

                @Override
                public void onFailure(String msg, int responseFailCode) {
                    btn_extract.setEnabled(false);
                    btn_extract.setBackgroundResource(R.drawable.button_corner_gray_shape);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initAdapter() {

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mActivity);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
//        recyclerView.addItemDecoration(new SpacesItemDecoration(10));
//        MiningOrderIncomeItem item = new MiningOrderIncomeItem();
//        item.setCreateTime("2019");
//        item.setMoney("300");
//        item.setChannelType(5);
//        item.setTypeName("挖矿收益");
//        item.setType(1);
//        datas.add(item);
        minerAdapter = new MinerIncomeAdapter(datas);
        recyclerView.setAdapter(minerAdapter);

//        minerAdapter.setOnItemClickListener((view, position) -> {
//            Token token = new Token(ConstantUtil.ETH_MAINNET, ConstantUtil.HMIO_TOKEN_SYMBOL, ConstantUtil.ETHEREUM_MAIN_ID);
//            Intent intent = new Intent(MinerIncomeActivity.this, MinerPayActivity.class);
//            token.setContractAddress(ConstantUtil.getHToken());// "0xb2054aDd212F19581aEB195FDa7644471a996134";
//            token.decimals = 18;
//            intent.putExtra(TransferActivity.EXTRA_TOKEN, token);
//            intent.putExtra(TransferActivity.EXTRA_ADDRESS, ConstantUtil.MINER_SELL_CONTRACT_TEST);
//            startActivity(intent);
//        });
    }

    private ProgressBar progressBar;
    ExtractDialog extractDialog;

    private void getConfirmTransferView() {
        if (detailBean == null) {
            Toast.makeText(mActivity, getString(R.string.network_error), Toast.LENGTH_SHORT).show();
            return;
        }
        BigDecimal withdrawMoney = new BigDecimal(detailBean.getMoney());
        if (withdrawMoney.compareTo(new BigDecimal(0.1)) < 0) {
            Toast.makeText(mActivity, getString(R.string.tip_minimum_withdrawal) + " 0.1ETH", Toast.LENGTH_SHORT).show();
            return;
        }
        if (isFastDoubleClick()) return;
//        String transferValue = transferValueEdit.getText().toString().trim();
//        String receiveAddress = mCetReceiverAddress.getText();
        extractDialog = new ExtractDialog(this, (password, progressBar) -> {
            this.progressBar = progressBar;
            extractDialog.setButtonClickAble(false);
            progressBar.setVisibility(View.VISIBLE);
            if (TextUtils.isEmpty(password)) {
                extractDialog.setButtonClickAble(true);
                progressBar.setVisibility(View.GONE);
                Toast.makeText(mActivity, R.string.password_not_null, Toast.LENGTH_SHORT).show();
            } else if (!WalletService.checkPassword(mActivity, password, DBWalletUtil.getCurrentWallet(this))) {
                extractDialog.setButtonClickAble(true);
                progressBar.setVisibility(View.GONE);
                Toast.makeText(mActivity, R.string.password_fail, Toast.LENGTH_SHORT).show();
            } else {
                extractIncome();
//                transferDialog.setButtonClickAble(false);
//                progressBar.setVisibility(View.VISIBLE);
//                mPresenter.handleTransferAction(password, transferValue, receiveAddress);
            }
        });
        extractDialog.setConfirmData(DBWalletUtil.getCurrentWallet(this).address,
                detailBean.getMoney() + "ETH",
                detailBean.getServiceCharge());
    }

//    private void getConfirmLockView() {
//        if (isFastDoubleClick()) return;
////        String transferValue = transferValueEdit.getText().toString().trim();
////        String transferValue1 = transferValueEdit1.getText().toString().trim();
////        String receiveAddress = mCetReceiverAddress.getText();
//           transferDialog = new TransferDialog(this, (password, progressBar) -> {
//            this.progressBar = progressBar;
//            Log.e("MainActivity","输入密码框1");
//            transferDialog.setButtonClickAble(false);
//            progressBar.setVisibility(View.VISIBLE);
//            if (TextUtils.isEmpty(password)) {
//                transferDialog.setButtonClickAble(true);
//                progressBar.setVisibility(View.GONE);
//                Toast.makeText(mActivity, R.string.password_not_null, Toast.LENGTH_SHORT).show();
//            } else if (!WalletService.checkPassword(mActivity, password, DBWalletUtil.getCurrentWallet(this))) {
//                transferDialog.setButtonClickAble(true);
//                progressBar.setVisibility(View.GONE);
//                Toast.makeText(mActivity, R.string.password_fail, Toast.LENGTH_SHORT).show();
//            } else {
//                Log.e("MainActivity","输入密码框2");
//                extractIncome();
//            }
//        });
//        transferDialog.confirmView.findViewById(R.id.rl_receive_address).setVisibility(View.GONE);
//        transferDialog.confirmView.findViewById(R.id.rl_pay_address).setVisibility(View.GONE);
////        transferDialog.setConfirmData(getString(R.string.commission_details), mPresenter.getWalletItem().address, receiveAddress,
////                NumberUtil.getDecimalValid_8(Double.parseDouble(transferValue)) + mPresenter.getTokenItem().getSymbol(),
////                feeValueText.getText().toString());
//        transferDialog.viewPager.setCurrentItem(1);
//    }

    private void extractIncome() {
        if (mData == null) {
            return;
        }
        String address = DBWalletUtil.getCurrentWallet(CytonApplication.getInstance()).address;
        try {
            Map params = MapUtils.newHashMap();
            params.put("address", address);
            params.put("moneyType", moneyType);
            String jsonData = GsonUtils.toJson(params);
            String content = RSAUtils.encrypt(jsonData);
            HttpRequestMode.getAddOrder(MyIncomeActivity.this, content, true, new CommonCallback() {
                @Override
                public void onSuccess(Object data, String successMsg, int responseSuccessCode) {
                    if (progressBar != null) {
                        progressBar.setVisibility(View.GONE);
                    }
                    if (extractDialog != null) {
                        extractDialog.dismiss();
                    }
                    ToastUtils.showLong(getString(R.string.withdrawal_success));
                }

                @Override
                public void onFailure(String msg, int responseFailCode) {
                    if (progressBar != null) {
                        progressBar.setVisibility(View.GONE);
                    }
                    if (extractDialog != null) {
                        extractDialog.dismiss();
                    }
                    ToastUtils.showLong(getString(R.string.withdrawal_fail));
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
